package com.bawei.wyg.mycommerce.test;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.bawei.wyg.mycommerce.R;

public class ViewModelActivity extends AppCompatActivity implements View.OnClickListener {
    Observer<String> dataOB;

    TextViewModel vm;
    private Button btn1;
    private Button btn2;
    private TextView tvVm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_model);
        initView();

        vm = new ViewModelProvider(this, new ViewModelProvider.Factory() {
            @NonNull
            @Override
            public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
                return (T) new TextViewModel();
            }
        }).get(TextViewModel.class);
        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        dataOB = new Observer<String>() {
            @Override
            public void onChanged(String s) {
                tvVm.setText(s);
            }
        };
        vm.data.observe(this, dataOB);
    }

    @Override
    protected void onPause() {
        super.onPause();
        vm.data.removeObserver(dataOB);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn1) {
            vm.data.setValue("猫晴呐~");
        } else if (id == R.id.btn2) {
            String value = vm.data.getValue();
            Log.i("WYG", "onClick: "+value);
        }
    }


    private void initView() {
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        tvVm = (TextView) findViewById(R.id.tv_vm);
    }
}